<template>
  <div class="t-card user-table">
    <div class="title">
      <div>
        <span>用户健康数据概览</span>
        <t-select
          v-model="selectedDisease"
          placeholder="选择疾病类型"
          :loading="diseaseLoading"
          clearable
          style="width: 200px; margin-left: 16px"
        >
          <t-option
            v-for="disease in diseaseOptions"
            :key="disease.id"
            :value="disease.id"
            :label="disease.name"
          />
        </t-select>
        <t-input
          v-model="formData.wxNickname"
          placeholder="请输入用户昵称/手机号"
          clearable
          style="width: 200px; margin-left: 14px"
        />
      </div>
      <div>
        <t-button @click="handleExport" :loading="exportUserLoading">导出用户数据</t-button>
        <t-button
          @click="handleExportArticle"
          :loading="exportArticleLoading"
          style="margin-left: 8px"
          >导出文章数据</t-button
        >
        <t-dropdown
          min-column-width="150px"
          :options="exportDropdownOptions"
          @click="handleDropdownExport"
          style="margin-left: 8px;"
        >
          <t-button :loading="exportDropdownLoading">
            更多导出
            <template #suffix>
              <t-icon name="chevron-down" />
            </template>
          </t-button>
        </t-dropdown>
      </div>
    </div>
    <t-table
      height="calc(100vh - 370px)"
      :data="tableData"
      :columns="columns"
      :pagination="pagination"
      :loading="loading"
      row-key="id"
      @page-change="onPageChange"
      bordered
    />
  </div>
</template>

<script>
import {
  getDataPanelUser,
  exportUserData,
  exportArticleData,
  exportPointsData,
  exportArticleLogData,
  exportArticleReviewLogData,
  exportArticleCountData
} from '@/api/data';
import { getDiseaseList } from '@/api/disease';
import { debounce } from 'lodash-es';

export default {
  name: 'UserTable',
  data() {
    return {
      selectedDisease: '',
      diseaseOptions: [],
      diseaseLoading: false,
      exportUserLoading: false,
      exportArticleLoading: false,
      exportDropdownLoading: false,
      exportDropdownOptions: [
        { content: '导出积分数据', value: 'points' },
        { content: '导出文章阅读数据', value: 'articleLog' },
        { content: '导出文章评分数据', value: 'articleReviewLog' },
        { content: '导出文章统计数据', value: 'articleCount' },
      ],
      tableData: [],
      loading: false,
      columns: [
        {
          title: '序号',
          colKey: 'index',
          width: 80,
          align: 'center',
          fixed: 'left',
          cell: (h, { rowIndex }) => {
            const index = (this.pagination.current - 1) * this.pagination.pageSize + rowIndex + 1;
            return h('span', index);
          },
        },
        {
          title: '微信昵称',
          colKey: 'wxNickname',
          width: 150,
          fixed: 'left',
          cell: (h, { row }) => {
            return h('span', row?.wechat?.nickname ?? '-');
          },
        },
        {
          title: '手机号',
          colKey: 'phone',
          width: 130,
          cell: (h, { row }) => {
            return h('span', row?.wechat?.phone ?? '-');
          },
        },
        {
          title: '年龄',
          colKey: 'age',
          width: 80,
          align: 'center',
          cell: (h, { row }) => {
            return h('span', row?.wechat?.age || '-');
          },
        },
        {
          title: '健康积分',
          colKey: 'healthScore',
          width: 100,
          align: 'center',
          cell: (h, { row }) => {
            const score = row?.wechat?.healthPoints || 0;
            return h('span', { style: { color: '#222' } }, score);
          },
        },
        {
          title: '知识积分',
          colKey: 'knowledgeScore',
          width: 100,
          align: 'center',
          cell: (h, { row }) => {
            const score = row?.knowledgePoints || 0;
            return h('span', { style: { color: '#222' } }, score);
          },
        },
        {
          title: '疾病类型',
          colKey: 'diseaseType',
          width: 120,
          align: 'center',
          cell: (h, { row }) => {
            const disease = row?.disease?.name || '无';
            const color = '#f7f7f7';
            return h(
              'span',
              {
                style: {
                  color: '#222',
                  backgroundColor: color,
                  padding: '2px 8px',
                  borderRadius: '4px',
                  fontSize: '13px',
                },
              },
              disease
            );
          },
        },
        {
          title: '阅读量',
          colKey: 'readingCount',
          width: 100,
          align: 'center',
          cell: (h, { row }) => {
            const count = row?.stats?.reading?.total || 0;
            return h('div', [
              h('span', { style: { color: '#222' } }, count),
              h('span', { style: { fontSize: '12px', marginLeft: '2px', color: '#999' } }, '篇'),
            ]);
          },
        },
        {
          title: '平均阅读时长',
          colKey: 'averageReadingTime',
          width: 120,
          align: 'center',
          cell: (h, { row }) => {
            const time = row?.stats?.readingDuration?.totalAverage || 0;
            let displayTime = '';
            let unit = '';

            if (time < 60) {
              // 小于60秒，显示秒
              displayTime = Math.round(time);
              unit = '秒';
            } else if (time < 3600) {
              // 小于1小时，显示分钟和秒
              const minutes = Math.floor(time / 60);
              const seconds = Math.round(time % 60);
              if (seconds > 0) {
                displayTime = `${minutes}分${seconds}`;
                unit = '秒';
              } else {
                displayTime = minutes;
                unit = '分钟';
              }
            } else {
              // 大于等于1小时，显示小时和分钟
              const hours = Math.floor(time / 3600);
              const minutes = Math.round((time % 3600) / 60);
              if (minutes > 0) {
                displayTime = `${hours}小时${minutes}`;
                unit = '分钟';
              } else {
                displayTime = hours;
                unit = '小时';
              }
            }

            return h('div', [
              h('span', { style: { color: '#222' } }, displayTime),
              h('span', { style: { fontSize: '12px', marginLeft: '2px', color: '#999' } }, unit),
            ]);
          },
        },
        {
          title: '收藏量',
          colKey: 'favoriteCount',
          width: 100,
          align: 'center',
          cell: (h, { row }) => {
            const count = row?.stats?.collects?.total || 0;
            return h('div', [
              h('span', { style: { color: '#222' } }, count),
              h('span', { style: { fontSize: '12px', marginLeft: '2px', color: '#999' } }, '个'),
            ]);
          },
        },
        {
          title: '点赞量',
          colKey: 'likeCount',
          width: 100,
          align: 'center',
          cell: (h, { row }) => {
            const count = row?.stats?.likes?.total || 0;
            return h('div', [
              h('span', { style: { color: '#222' } }, count),
              h('span', { style: { fontSize: '12px', marginLeft: '2px', color: '#999' } }, '个'),
            ]);
          },
        },
        {
          title: '完成任务量',
          colKey: 'taskCompletion',
          width: 120,
          align: 'center',
          cell: (h, { row }) => {
            const count = row?.stats?.tasks?.total || 0;
            return h('div', [
              h('span', { style: { color: '#222' } }, count),
              h('span', { style: { fontSize: '12px', marginLeft: '2px', color: '#999' } }, '个'),
            ]);
          },
        },
        {
          title: '答题正确率',
          colKey: 'quizAccuracy',
          width: 120,
          align: 'center',
          cell: (h, { row }) => {
            const rate = row?.stats?.quiz?.totalCorrectRate || 0;
            return h('div', [
              h('span', { style: { color: '#222' } }, rate),
              h('span', { style: { fontSize: '12px', marginLeft: '2px', color: '#999' } }, '%'),
            ]);
          },
        },
        {
          title: 'BMI',
          colKey: 'bmi',
          width: 100,
          align: 'center',
          cell: (h, { row }) => {
            const bmi = parseFloat(row?.wechat?.bmi) || 0;
            return h('span', { style: { color: '#222' } }, bmi.toFixed(1));
          },
        },
        {
          title: '血压(mmHg)',
          colKey: 'bloodPressure',
          width: 120,
          align: 'center',
          cell: (h, { row }) => {
            const systolic = row?.wechat?.bloodPressureSbp || 0;
            const diastolic = row?.wechat?.bloodPressureDbp || 0;
            const pressure = `${systolic}/${diastolic}`;
            return h('span', { style: { color: '#222' } }, pressure);
          },
        },
        {
          title: '空腹血糖(mmol/L)',
          colKey: 'bloodSugar',
          width: 150,
          align: 'center',
          cell: (h, { row }) => {
            const sugar = parseFloat(row?.wechat?.fastingBloodGlucose) || 0;
            return h('span', { style: { color: '#222' } }, sugar.toFixed(1));
          },
        },
        {
          title: '低密度脂蛋白(mmol/L)',
          colKey: 'ldl',
          width: 180,
          align: 'center',
          cell: (h, { row }) => {
            const ldl = parseFloat(row?.wechat?.ldlCholesterol) || 0;
            return h('span', { style: { color: '#222' } }, ldl.toFixed(1));
          },
        },
        {
          title: '血尿酸(μmol/L)',
          colKey: 'uricAcid',
          width: 150,
          align: 'center',
          cell: (h, { row }) => {
            const uricAcid = parseFloat(row?.wechat?.uricAcid) || 0;
            return h('span', { style: { color: '#222' } }, uricAcid.toFixed(0));
          },
        },
      ],
      pagination: {
        current: 1,
        total: 100,
        pageSize: 20,
      },
      formData: {
        diseaseType: '',
        wxNickname: '',
        phone: '',
      },
      debouncedSearch: null, // 用来存防抖函数
    };
  },
  mounted() {
    this.getDiseaseList();
    this.getUserData();

    this.debouncedSearch = debounce(() => {
      this.pagination.current = 1;
      this.getUserData();
    }, 800); // 500ms 防抖间隔
  },
  watch: {
    selectedDisease() {
      this.pagination.current = 1;
      this.getUserData();
    },
    'formData.wxNickname'() {
      // 输入框变化时进行搜索
      // this.pagination.current = 1;
      // this.getUserData();
      this.debouncedSearch();
    },
  },
  methods: {
    // 获取用户数据
    async getUserData() {
      this.loading = true;
      try {
        const params = {
          page: this.pagination.current,
          pageSize: this.pagination.pageSize,
          keyword: this.formData.wxNickname,
          diseaseId: this.selectedDisease,
        };

        const response = await getDataPanelUser(params);
        console.log(response);
        if (response && response.data) {
          this.tableData = response?.data?.data?.data ?? [];
          this.pagination.total = response?.data?.data?.total ?? 0;
        }
      } catch (error) {
        console.error('获取用户数据失败:', error);
        this.$message.error('获取用户数据失败');
      } finally {
        this.loading = false;
      }
    },
    onPageChange(curr) {
      this.pagination.current = curr.current;

      if (this.pagination.pageSize !== curr.pageSize) {
        this.pagination.pageSize = curr.pageSize;
        this.pagination.current = 1;
      }

      this.getUserData();
    },
    onSearch() {
      this.pagination.current = 1;
      this.getUserData();
    },
    onReset() {
      this.selectedDisease = '';
      this.formData.wxNickname = '';
      this.pagination.current = 1;
      this.getUserData();
    },
    async handleExport() {
      this.exportUserLoading = true;
      try {
        const params = {
          keyword: this.formData.wxNickname,
          diseaseId: this.selectedDisease,
        };

        const response = await exportUserData(params);

        // 创建下载链接
        const blob = new Blob([response.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `用户数据_${new Date().toISOString().split('T')[0]}.xlsx`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        this.$message.success('用户数据导出成功');
      } catch (error) {
        console.error('导出用户数据失败:', error);
        this.$message.error('导出用户数据失败');
      } finally {
        this.exportUserLoading = false;
      }
    },
    async handleExportArticle() {
      this.exportArticleLoading = true;
      try {
        const response = await exportArticleData();

        // 创建下载链接
        const blob = new Blob([response.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `文章数据_${new Date().toISOString().split('T')[0]}.xlsx`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        this.$message.success('文章数据导出成功');
      } catch (error) {
        console.error('导出文章数据失败:', error);
        this.$message.error('导出文章数据失败');
      } finally {
        this.exportArticleLoading = false;
      }
    },
    // 处理下拉导出
    async handleDropdownExport(data) {
      this.exportDropdownLoading = true;
      try {
        let response;
        let fileName;
        let successMessage;

        switch (data.value) {
          case 'points':
            response = await exportPointsData();
            fileName = `积分数据_${new Date().toISOString().split('T')[0]}.xlsx`;
            successMessage = '积分数据导出成功';
            break;
          case 'articleLog':
            response = await exportArticleLogData();
            fileName = `文章日志数据_${new Date().toISOString().split('T')[0]}.xlsx`;
            successMessage = '文章日志数据导出成功';
            break;
          case 'articleReviewLog':
            response = await exportArticleReviewLogData();
            fileName = `文章评分日志数据_${new Date().toISOString().split('T')[0]}.xlsx`;
            successMessage = '文章评分日志数据导出成功';
            break;
          case 'articleCount':
            response = await exportArticleCountData();
            fileName = `文章相关统计数据_${new Date().toISOString().split('T')[0]}.xlsx`;
            successMessage = '文章相关统计数据导出成功';
            break;
          default:
            this.$message.error('未知的导出类型');
            return;
        }

        // 创建下载链接
        const blob = new Blob([response.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        this.$message.success(successMessage);
      } catch (error) {
        console.error('导出数据失败:', error);
        this.$message.error('导出数据失败');
      } finally {
        this.exportDropdownLoading = false;
      }
    },
    async getDiseaseList() {
      this.diseaseLoading = true;
      try {
        const response = await getDiseaseList();
        if (response && response.data) {
          this.diseaseOptions = response.data.data || [];
        }
      } catch (error) {
        console.error('获取疾病列表失败:', error);
        this.$message.error('获取疾病列表失败');
      } finally {
        this.diseaseLoading = false;
      }
    },
  },
};
</script>

<style scoped lang="less">
.user-table {
  margin-top: 14px;
  box-sizing: border-box;
  padding: 14px;

  :deep(.t-table__header) {
    background-color: #f5f5f5;
  }

  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    color: #222;
    font-size: 16px;
    font-weight: bold;

    & > div {
      display: flex;
      align-items: center;
    }
  }

  .search-form {
    margin-bottom: 16px;

    /deep/ .t-form__label {
      padding-right: 8px;
    }
  }
}
</style>
